﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ImportObs
{
    static FileStream fs;

    [MenuItem("Tools/ImportObs", false, 10)]
    static void Import()
    {
        if (OpenObsDataFile())
        {
            ReadObsData();
            fs.Close();
        }
    }

    public static bool OpenObsDataFile()
    {
        string obsFilePath = Application.dataPath + @"/Obs.data";
        try
        {
            fs = File.Open(obsFilePath, FileMode.Open);
        }
        catch (IOException e)
        {
            Debug.Log(e.Message);
            return false;
        }
        return true;
    }

    static void ReadObsData()
    {
        BinaryReader br = new BinaryReader(fs);
        UInt16 size = br.ReadUInt16();
        Vector3 tempPos = Vector3.one;

        for (UInt16 i = 0; i < size; i++)
        {
            for (UInt16 j = 0; j < size; j++)
            {
                if (br.ReadBoolean())
                {
                    tempPos.z = i;
                    tempPos.x = j;
                    tempPos.y = GetHeight(tempPos);
                    tempPos.z += 0.5f;
                    tempPos.x += 0.5f;
                    DrawObs(tempPos);
                }
            }
        }
    }

    static float GetHeight(Vector3 pos)
    {
        Ray mRay = new Ray();
        Vector3 dir = Vector3.down;
        if (Terrain.activeTerrain == null)
        {
            return pos.y;
        }

        mRay.direction = dir;
        pos.y += 1000; mRay.origin = pos;
        RaycastHit[] hits = Physics.RaycastAll(mRay, 2000);
        if (hits.Length == 0) { return pos.y; }

        float maxHeight = 0.0f; //找出碰撞点里面的最高点
        for (int index = 0; index < hits.Length; index++)
        {
            var go = hits[index].collider.gameObject;
            if (go.layer == LayerMask.NameToLayer("Terrain"))  //记得给layer加上Terrain
            {
                if (hits[index].point.y > maxHeight)
                {
                    maxHeight = hits[index].point.y;
                }
            }
            else { continue; }
        }
        return maxHeight + 0.1f;
    }

    static void DrawObs(Vector3 pos)
    {
        GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        cube.transform.position = pos;
    }
}